<template>
  <div class="app-container">
    <el-row style="padding-bottom: 20px" v-if="useUserStore().userType === '1' || useUserStore().userType === '2'">
      <el-col :span="4">
        <el-card shadow="always"> <span>账户余额：{{walletForm.balance}}</span></el-card>
      </el-col>
      <el-col :span="4" style="margin-left: 20px">
        <el-card shadow="always"> <span>已提现金额：{{walletForm.withdrawn}}</span></el-card>
      </el-col>
<!--      <el-col :span="4" style="margin-left: 20px">-->
<!--        <el-card shadow="always"> <span>审核中金额：{{walletForm.inReview}}</span></el-card>-->
<!--      </el-col>-->
    </el-row>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option
              v-for="dict in shop_examine_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提现类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择提现类型" clearable>
          <el-option
              v-for="dict in withdrawal_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['pay:wallet:add']"
        >发起提现
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="walletAuditList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="提现金额" align="center" prop="balance"/>
      <el-table-column label="提现类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="withdrawal_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="支付宝账号" width="150" align="center" prop="alipayAccount"/>
      <el-table-column label="银行卡号" width="250" align="center" prop="bankcardNumber"/>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template #default="scope">
          <dict-tag :options="shop_examine_status" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)">详情</el-button>
          <el-button link type="primary"
                     :class="{'but-disabled': !(scope.row.auditStatus === '09' || scope.row.auditStatus === '03')}"
                     icon="Edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button link type="primary"
                     :class="{'but-disabled': !(scope.row.auditStatus === '09' || scope.row.auditStatus === '03')}"
                     icon="Position" @click="initiationOrWithdrawal(scope.row,'00')">发起</el-button>
          <el-button link type="primary"
                     :class="{'but-disabled': !(scope.row.auditStatus === '00')}"
                     icon="CloseBold" @click="initiationOrWithdrawal(scope.row,'03')">撤回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <el-dialog :title="title" v-model="addOpen" width="1000px" append-to-body>
      <el-form ref="walletRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="提现金额" prop="balance">
              <el-input-number v-model="form.balance" placeholder="请输入提现金额" min="0" :precision="2" :controls="false"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提现类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择提现类型">
                <el-option
                    v-for="dict in withdrawal_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === '2'">
            <el-form-item label="支付宝号" prop="alipayAccount">
              <el-input v-model="form.alipayAccount" placeholder="请输入支付宝账号" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12" v-if="form.type === '2' || form.type === '3'">-->
<!--            <el-form-item label="收款码" prop="paymentCode">-->
<!--              <image-upload v-model="form.paymentCode" :limit="1"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === '1'">
            <el-form-item label="银行卡号" prop="bankcardNumber">
              <el-input v-model="form.bankcardNumber" placeholder="请输入银行卡号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === '1'">
            <el-form-item label="手机号" prop="bankcardPhone">
              <el-input v-model="form.bankcardPhone" placeholder="请输入银行卡绑定手机号"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm('09')">确 定</el-button>
          <el-button @click="addOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改提现审核对话框 -->
    <el-dialog title="审核详情" v-model="open" width="700px" append-to-body>
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请人：">{{ form.userName }}</el-form-item>
            <el-form-item
                label="申请金额："
            >{{ form.balance }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型：">
              <dict-tag :options="wallet_type" :value="form.walletType"/>
            </el-form-item>
            <el-form-item label="联系方式：">{{ form.phone }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提现类型：">
              <dict-tag :options="withdrawal_type" :value="form.type"/>
            </el-form-item>
            <el-form-item label="联系方式：">{{ form.phone }}</el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === '2'">
            <el-form-item label="支付宝号：">{{ form.alipayAccount }}</el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === '2' || form.type === '3'">
            <el-form-item label="收款码：" prop="mainPic">
              <image-preview :src="form.paymentCode" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === '1'">
            <el-form-item label="银行卡号：">{{ form.bankcardNumber }}</el-form-item>
            <el-form-item label="手机号：">{{ form.bankcardPhone }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态：">
              <dict-tag :options="shop_examine_status" :value="form.auditStatus"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核节点：">
              <div style="height: 300px">
                <el-steps :space="400" style="width: 400px"
                          :active="(form.auditStatus === '00')?form.stepType-1:form.stepType"
                          :finish-status="finishStatus">
                  <el-step v-for="step in form.walletAuditStep" :title="step.stepName"/>
                </el-steps>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WalletAudit">
import {
  listUserWalletAudit,
  getWalletAudit,
  submitWalletAuditExamine,
  updateWalletAuditExamine
} from "@/api/pay/walletAudit";
import {getWalletInfo} from "@/api/pay/wallet";
import useUserStore from '@/store/modules/user'
import {onBeforeUnmount, watch} from "vue";
const {proxy} = getCurrentInstance();
const {shop_examine_status, withdrawal_type} = proxy.useDict('shop_examine_status','withdrawal_type','wallet_type')

const walletAuditList = ref([]);
const open = ref(false);
const addOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
let finishStatus = ref("");

const data = reactive({
  form: {},
  walletForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bankcardNumber: undefined,
    bankcardPhone: undefined,
    auditStatus: undefined,
  },
  rules: {
    type:[
      {required: true, message: "请选择提现类型！", trigger: "blur"},
    ],
    alipayAccount:[
      {required: true, message: "请输入支付宝账号！", trigger: "blur"},
      { pattern: /^[a-zA-Z0-9]{6,30}$/, message: "支付宝账号必须为6-30个字符，可以包含数字和字母！", trigger: "blur" }
    ],
    // paymentCode:[
    //   {required: true, message: "请上传收款码！", trigger: "blur"},
    // ],
    bankcardNumber:[
      {required: true, message: "请输入银行卡号！", trigger: "blur"},
      { pattern: /^[0-9]{16,19}$/, message: "银行卡号必须为16-19个数字！", trigger: "blur" }
    ],
    balance:[
      {required: true, message: "金额不能为空！", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (value > 0) {
            callback();
          } else {
            callback(new Error("金额必须大于0"));
          }
        },
        trigger: "blur"
      },
      {
        validator: (rule, value, callback) => {
          if (walletForm.value.balance > value) {
            callback();
          } else {
            callback(new Error("余额不足"));
          }
        },
        trigger: "blur"
      }
    ],
    bankcardPhone:[
      {required: true, message: "手机号不能为空！", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          const reg = /^[1][3-9]\d{9}$/;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("请输入有效的手机号"));
          }
        },
        trigger: "blur"
      }
    ]
  }
});

const {queryParams, form, rules, walletForm} = toRefs(data);

/** 查询提现审核列表 */
function getList() {
  loading.value = true;
  listUserWalletAudit(queryParams.value).then(response => {
    walletAuditList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  if (useUserStore().userType === '1' || useUserStore().userType === '2') {
    getWalletInfo().then(response => {
      walletForm.value = response.data;
      console.log(walletForm.value)
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    walletId: undefined,
    balance: undefined,
    type: undefined,
    alipayAccount: undefined,
    paymentCode: undefined,
    bankcardNumber: undefined,
    bankcardPhone: undefined,
    auditStatus: undefined,
    auditorId: undefined,
    createTime: undefined,
    updateTime: undefined
  };
  proxy.resetForm("walletAuditRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  addOpen.value = true;
  title.value = "发起提现审核";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getWalletAudit(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改提现审核";
  });
}

/** 提交按钮 */


function submitForm(status) {
  proxy.$refs["walletRef"].validate(valid => {
    if (valid) {
      form.value.walletId = walletForm.value.id;
      form.value.auditStatus = status;
      submitWalletAuditExamine(form.value).then(response => {
        proxy.$modal.msgSuccess("提交成功");
        addOpen.value = false;
        getList();
      });
    }
  });
}

function initiationOrWithdrawal(data,status) {
  proxy.$modal.confirm(status === '00'?'是否确认提交审核':'是否确认撤回申请').then(function() {
    data.auditStatus = status;
    submitWalletAuditExamine(data).then(response => {
      proxy.$modal.msgSuccess("操作成功");
      getList();
    });
  }).catch(() => {
  });
}


/** 详细按钮操作 */
function handleView(row) {
  const _id = row.id
  getWalletAudit(_id).then(response => {
    form.value = response.data;
    if (form.value.auditStatus === '01' || form.value.auditStatus === '2') {
      finishStatus.value = 'success';
    }
    open.value = true;
  });
}
getList();
const stopWatching = watch(() => useUserStore().cascaderKey, (v) => {
  getList();
}, { immediate: true });
onBeforeUnmount(() => {
  stopWatching();
});
</script>
